package com.wechat.scheme.handler;

import cn.hutool.core.util.RandomUtil;
import com.wechat.scheme.builder.ImageBuilder;
import com.wechat.scheme.builder.TextBuilder;
import com.wechat.scheme.repo.BaiduSourceRepo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import me.chanjar.weixin.mp.builder.outxml.VoiceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;


@Slf4j
@Component
public class MsgVoiceHandler extends AbstractHandler {

    private static final String temple_str = "抱歉,-_-暂时不支持语音智能识别,功能开发ing";


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }
        try {
            WxMpMaterialService wxMpMaterialService = new WxMpMaterialServiceImpl(weixinService);
            WxMpMaterialFileBatchGetResult result = wxMpMaterialService.materialFileBatchGet(WxConsts.MediaFileType.VIDEO, 0, 20);
            int randomIndex = RandomUtil.randomInt(result.getItemCount() - 1);
            if(result.getTotalCount()>0){
                log.info("VIDEO msg temple size: {},randomIndex:{}",result.getTotalCount(),randomIndex);
                String mediaId = result.getItems().get(randomIndex).getMediaId();
                return new VoiceBuilder().mediaId(mediaId).fromUser(wxMessage.getFromUser()).toUser(wxMessage.getToUser()).build();
            }
            return new TextBuilder().build(temple_str, wxMessage, weixinService);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new TextBuilder().build(temple_str, wxMessage, weixinService);
        }finally {
        }

    }

}
